// src/data-generator/data-generator.service.ts
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { ServersService } from '../servers/servers.service';
import { ServerMetric } from '../entities/server-metric.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { ProjectsService } from '../projects/projects.service';
import { ProjectMetric } from '../entities/project-metric.entity';
import { EventLog } from '../entities/event-log.entity';
import { Alert } from '../entities/alert.entity';

// 添加pickRandom函数实现
function pickRandom<T>(array: T[]): T {
  return array[Math.floor(Math.random() * array.length)];
}

@Injectable()
export class DataGeneratorService {
  constructor(
    private readonly serversService: ServersService,
    private readonly projectsService: ProjectsService, // ✅ 注入
    @InjectRepository(ServerMetric)
    private readonly serverMetricRepository: Repository<ServerMetric>,
    @InjectRepository(ProjectMetric)
    private readonly projectMetricRepository: Repository<ProjectMetric>, // ✅ 注入
    @InjectRepository(EventLog)
    private readonly logRepo: Repository<EventLog>,
    @InjectRepository(Alert)
    private readonly alertRepo: Repository<Alert>,
  ) {}
  @Cron('*/500 * * * * *') // 每5秒
  async simulateEvents() {
    const sources = ['server-01', 'api-gateway', 'auth-service'];
    const levels: ('INFO' | 'WARN' | 'ERROR' | 'CRITICAL')[] = [
      'INFO',
      'WARN',
      'ERROR',
    ];
    const messages = [
      'User login successful',
      'Database connection timeout',
      'High CPU usage detected',
      'Cache hit rate low',
    ];

    if (Math.random() < 0.7) {
      const log = this.logRepo.create({
        source: pickRandom(sources),
        level: pickRandom(levels),
        message: pickRandom(messages),
      });
      await this.logRepo.save(log);
      // 注释掉未定义的logsGateway相关代码
      // this.logsGateway.server.emit('new-logs', [log]); // 实时推送
    }
  }

  @Cron('*/3000 * * * * *') // 每30秒
  async generateAlerts() {
    if (Math.random() < 0.3) {
      const servers = await this.serversService.findAll();
      const server = servers.length > 0 ? servers[0] : null;

      if (server) {
        const alert = this.alertRepo.create({
          title: 'High CPU Usage',
          level: 'high',
          status: 'pending',
          server: server,
        });
        await this.alertRepo.save(alert);
        // 注释掉未定义的alertsGateway相关代码
        // this.alertsGateway.server.emit('new-alert', alert);
      }
    }
  }
  @Cron('*/1000 * * * * *') // 每10秒执行
  async generateServerMetrics() {
    const servers = await this.serversService.findAll();

    for (const server of servers) {
      const baseCpu = 40 + Math.sin(Date.now() / 10000) * 20;
      const randomNoise = (Math.random() - 0.5) * 10;
      const spike = Math.random() < 0.05 ? 30 : 0;
      const cpu = Math.min(95, Math.max(5, baseCpu + randomNoise + spike));
      const memory =
        50 + Math.sin(Date.now() / 12000) * 25 + (Math.random() - 0.5) * 10;
      const disk = 60 + Math.random() * 20;

      const metric = this.serverMetricRepository.create({
        server,
        cpuUsage: Number(cpu.toFixed(2)),
        memoryUsage: Number(memory.toFixed(2)),
        diskUsage: Number(disk.toFixed(2)),
        networkIn: Math.floor(Math.random() * 1000000),
        networkOut: Math.floor(Math.random() * 800000),
      });

      await this.serverMetricRepository.save(metric);
    }

    console.log(
      `✅ Generated metrics for ${servers.length} servers at ${new Date().toISOString()}`,
    );
  }
  @Cron('*/1500 * * * * *') // 每15秒执行
  async generateProjectMetrics() {
    const projects = await this.projectsService.findAll();

    for (const project of projects) {
      const cpu = Math.floor(20 + Math.random() * 70); // 20% ~ 90%
      const memory = Math.floor(30 + Math.random() * 60); // 30% ~ 90%
      const requests = Math.floor(Math.random() * 100);
      const errors = Math.random() < 0.02 ? Math.floor(Math.random() * 5) : 0;
      const responseTime = 50 + Math.random() * 450; // 50ms ~ 500ms

      const metric = this.projectMetricRepository.create({
        project,
        cpuUsage: cpu,
        memoryUsage: memory,
        requestCount: requests,
        errorCount: errors,
        responseTime: parseFloat(responseTime.toFixed(2)),
      });

      await this.projectMetricRepository.save(metric);
    }

    console.log(`✅ 已生成 ${projects.length} 个项目的监控数据`);
  }
}
